package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;


/**
 * 使用注解时,Controller类型也可以是普通类型
 * 但是需要标注@Controller注解
 */
@Controller
@RequestMapping("/dev") //加一层前缀
public class HelloController  {
    private static final Logger LOGGER = LoggerFactory.getLogger(HelloController.class);
    /**
     * 使用注解时,控制器方法是一个普通方法,
     * 由@RequestMapping注解映射请求路径
     */
    @RequestMapping("/hello")
    protected ModelAndView hello(@RequestParam(name="realName",required = false) String name) throws Exception {
        LOGGER.info("你好{},欢迎学习SpringMVC!",name);
        ModelAndView modelAndView = new ModelAndView();
        //添加数据模型到Model模型数据中
        modelAndView.addObject("realName",name);
        //设置逻辑视图名
        modelAndView.setViewName("hello");
        //返回字符串结果作为逻辑视图名
        return modelAndView;
    }
    //一个控制器类中可以定义多个方法
    @RequestMapping("/welcome")
    private String welcome(HttpServletRequest request) throws Exception {
        LOGGER.info("进入控制器welcome方法,请求路径:{}",request.getRequestURI());
        return "hello";
    }
    @RequestMapping("/model")
    public String model(Map map, @RequestParam(name="realName",required = false) String name) throws Exception {
        LOGGER.info("你好{},在参数注入的Model对象也可以出参!",name);
        //使用model对象添加数据
        map.put("realName",name);
        //创建SysUser对象,并存入model对象
        SysUser sysUser = new SysUser();
        sysUser.setRealName(name);
        map.put("sysUser",sysUser);
        return "hello";
    }
}